<?php
class IndexController extends Zend_Controller_Action {
	
	public function init() {
		/* Initialize action controller here */
	}

	public function indexAction() {
		// action body
	}

	public function renderAction() {
		$menu = $this->_request->getParam('menu');
		// fetch the Zend_Cache object
		$bootstrap = $this->getInvokeArg('bootstrap');
		$cache = $bootstrap->getResource('cache');
		$cacheKey = 'menu_' . $menu;
		// attempt to load the menu from cache
		$container = $cache->load($cacheKey);
		if (! $container) {
			// if the menu is not cached then build it and cache it
			$mdlMenuItems = new Model_MenuItem();
			$menuItems = $mdlMenuItems->getItemsByMenu($menu);
			if (count($menuItems) > 0) {
				foreach ($menuItems as $item) {
					// add a cache tag so you can update the menu when you update the items
					$tags[] = 'menu_item_' . $item->id;
					$label = $item->label;
					if (!empty($item->link)) {
						$uri = $item->link;
					} else {
						// add a cache tag to this menu so you can update the cached menu
						// when you update the page
						$tags[] = 'page_' . $item->page_id;
						// update this to form more search engine friendly URLs
						$page = new CMS_Content_Item_Page($item->page_id);
						$uri = '/index/open/title/' . $page->name;
					}
					$itemArray[] = array('label' => $label , 'uri' => $uri);
				}
				$container = new Zend_Navigation($itemArray);
				// cache the container
				$cache->save($container, $cacheKey, $tags);
			}
		}
		if($container instanceof Zend_Navigation_Container) {
			$this->view->navigation()->setContainer($container);
		}
	}

	public function openAction() {
		$title = $this->_request->getParam('title');
		$mdlPage = new Model_Page();
		$row = null;
		if (null !== $title) {
			$select = $mdlPage->select();
			$select->where('name = ?', $title);
			$row = $mdlPage->fetchRow($select);
			$id = $row->id;
		} else {
			$id = $this->_request->getParam('id');
		}
		// first confirm the page exists
		$bootstrap = $this->getInvokeArg('bootstrap');
		$cache = $bootstrap->getResource('cache');
		$cacheKey = 'content_page_' . $id;
		$page = $cache->load($cacheKey);
		if(!$page) {
			if($row instanceof Zend_Db_Table_Row) {
				$page = new CMS_Content_Item_Page($row);
			} else {
				$page = new CMS_Content_Item_Page($id);
			}
			// add a cache tag to this menu so you can update the cached menu
			// when you update the page
			$tags[] = 'page_' . $page->id;
			$cache->save($page, $cacheKey, $tags);
		}
		$this->view->page = $page;
	}
}